<template>
    <div class="main-content">
        <!-- 表格工具栏 -->
        <div class="table-toolbar">
            <el-input v-model="searchParams.keyword" placeholder="请输入条款编号/名称" size="mini" style="width: 220px; margin-right: 10px">
            </el-input>
            <el-button type="primary" size="mini" v-authCode.show="showAuthBtn('search')" @click="handleBtn('search')">查询</el-button>
            <el-button type="primary" size="mini" v-authCode.show="showAuthBtn('add')" @click="handleBtn('add')">新增</el-button>
            <el-button type="danger" size="mini" v-authCode.show="showAuthBtn('delete')" @click="handleBtn('delete')">删除</el-button>
            <el-button type="primary" size="mini" v-authCode.show="showAuthBtn('export')" @click="handleBtn('export')">条款导出</el-button>
            <el-checkbox
                v-model="searchParams.showEffectSource"
                label="showEffectSource"
                @change="handleBtn('showEffectSource')"
                style="margin-left: 10px"
                >只展示生效状态来源下的条款</el-checkbox
            >
            <el-button type="primary" size="mini" v-authCode.show="showAuthBtn('layout')" @click="layoutDialog = true" class="right-box"
                >布局设置</el-button
            >
        </div>
        <RiskTableP
            ref="risk-table"
            :tableData="tableData"
            :tableConfig="tableConfig"
            :column="showColumns"
            :paging="paging"
            v-loading="tableLoading"
            minWidth="120px"
            class="table"
            :key="tableKey"
            :searchParams="searchParams"
            @page-change="pageChange"
        >
            <template #operation="{ row }">
                <RiskIconButton
                    type="primary"
                    icon="el-icon-view"
                    topTitle="查看来源"
                    size="mini"
                    v-authCode="showAuthBtn('row-look')"
                    @on-click="handleRowData('look', row)"
                ></RiskIconButton>
                <RiskIconButton
                    type="primary"
                    icon="el-icon-edit"
                    topTitle="编辑来源"
                    size="mini"
                    v-authCode="showAuthBtn('row-edit')"
                    @on-click="handleRowData('edit', row)"
                ></RiskIconButton>
                <RiskIconButton
                    type="danger"
                    icon="el-icon-delete"
                    topTitle="删除条款"
                    size="mini"
                    v-authCode="showAuthBtn('row-delete')"
                    @on-click="handleRowData('delete', row)"
                ></RiskIconButton>
            </template>
        </RiskTableP>

        <!-- 查看、编辑、新增 -->
        <el-dialog
            :title="currentRow.showDialogTitle"
            :visible.sync="basicInfoVisible"
            width="90%"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            class="basic-info-dialog"
            top="5vh"
        >
            <ClauseManageInfo :info="currentRow" ref="basic-info" v-if="basicInfoVisible" />
            <div slot="footer" class="dialog-footer">
                <el-button @click="BasicDialogBtn('cancel')">取 消</el-button>
                <el-button
                    type="primary"
                    @click="BasicDialogBtn('confirm')"
                    v-if="currentRow.operationType == 'edit' || currentRow.operationType == 'add'"
                    >确 定</el-button
                >
            </div>
        </el-dialog>

        <!-- 布局设置 -->
        <RiskTableLayout
            ref="risk-table-layout"
            :tableName="'CLAUSE_MANAGE_TEST'"
            :visible.sync="layoutDialog"
            :column="columns"
            :fixedColumns="fixedColumns"
        />

        <!-- 导出 -->
        <el-dialog title="导出" :visible.sync="exportVisible" width="30%" :close-on-click-modal="false" :close-on-press-escape="false">
            文件名：<el-input v-model="exportName" size="mini"></el-input>
            <div slot="footer" class="dialog-footer">
                <el-button @click="exportVisible = false">取 消</el-button>
                <el-button type="primary" @click="exportDialogBtn()">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 删除 -->
        <el-dialog
            title="确定删除以下条款吗？"
            :visible.sync="deleteVisible"
            width="30%"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <div>条款编号：{{ checkRowKeys.join(',') }}</div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="deleteDialogBtn('cancel')">取 消</el-button>
                <el-button type="primary" @click="deleteDialogBtn('confirm')">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { ColumnVO, PageVO, TableConfigVO, VueObject } from '@/common/vo';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { clauseManageDTO, clauseManageReqVO } from '../../vo';
import API from '../../api/index';
import RiskTableLayout from '@/common/components/risk-table-layout-plus.vue';
import Dict from '../../dict/index';
import DictionConstUtil from '@/utils/diction-const-util';
import ClauseManageInfo from './clause-manage-info.vue';
@Component({ name: 'ClauseManage', components: { RiskTableP, RiskIconButton, RiskTableLayout, ClauseManageInfo } })
export default class ClauseManage extends Vue {
    Dict = new Dict();
    tableConfig: TableConfigVO = {
        rowKey: 'termCode_', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    tableData: clauseManageDTO[] = [
        {
            termCode_: 'TK167', // 条款编号,
            termId_: '第一条', // 条款号,
            termName_: '本计划的总资产不得超过10%', // 条款名称,
            termRead_: '本计划的总资产...', // 条款解读
            suitableFund_: '公募-股票基金', // 条款适用产品,
            suitableExemptFund_: '101-日增利1号', // 条款豁免产品,
            O32support_: '支持', // O32系统支持情况
            Yhsupport_: '支持', // YH系统支持情况
            sourceType_: '法律规定', // 来源类型,
            sourceGroupType_: '证监会', // 来源分组
            sourceCode_: 'YH001', // 来源编号,
            sourceName_: '中国证券登记结算指引', // 来源名称,
            sourceVisible_: '2023版', // 来源版本号,
            sourceSuitableFund_: '公募-股票基金', // 来源适用产品,
            sourceStatus_: '生效', // 来源状态
            termCreator_: 'testuser1', // 创建人,
            termCreatDate_: '2021-08-20 12:00:02', // 创建时间,
            termModifier_: 'testuser1', // 更新人,
            termModuifyDate_: '2021-08-20 12:00:02', // 更新时间,
        },
        {
            termCode_: 'TK178', // 条款编号,
            termId_: '第一条', // 条款号,
            termName_: '本计划的总资产不得超过10%', // 条款名称,
            termRead_: '本计划的总资产...', // 条款解读
            suitableFund_: '公募-股票基金', // 条款适用产品,
            suitableExemptFund_: '101-日增利1号', // 条款豁免产品,
            O32support_: '支持', // O32系统支持情况
            Yhsupport_: '支持', // YH系统支持情况
            sourceType_: '法律规定', // 来源类型,
            sourceGroupType_: '证监会', // 来源分组
            sourceCode_: 'YH001', // 来源编号,
            sourceName_: '中国证券登记结算指引', // 来源名称,
            sourceVisible_: '2023版', // 来源版本号,
            sourceSuitableFund_: '公募-股票基金', // 来源适用产品,
            sourceStatus_: '生效', // 来源状态
            termCreator_: 'testuser1', // 创建人,
            termCreatDate_: '2021-08-20 12:00:02', // 创建时间,
            termModifier_: 'testuser1', // 更新人,
            termModuifyDate_: '2021-08-20 12:00:02', // 更新时间,
        },
    ];
    columns: ColumnVO[] = [
        {
            type: 'checkbox',
            selectedAll: false,
            fixed: 'left',
            align: 'center',
            width: 60,
        },
        {
            field: 'termCode_',
            title: '条款编号',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'termId_',
            title: '条款号',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'termName_',
            title: '条款名称',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'termRead_',
            title: '条款解读',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'suitableFund_',
            title: '条款适用产品',
            minWidth: '160px',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'suitableExemptFund_',
            title: '条款豁免产品',
            minWidth: '150px',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'O32support_',
            title: 'O32系统支持情况',
            minWidth: '160px',
            sortable: true,
            filterType: 'funnel',
            filters: [],
        },
        {
            field: 'Yhsupport_',
            title: 'YH系统支持情况',
            minWidth: '160px',
            sortable: true,
            filterType: 'funnel',
            filters: [{ data: '' }],
        },
        {
            field: 'sourceType_',
            title: '来源类型',
            minWidth: '140px',
            sortable: true,
            filterType: 'funnel',
            filters: [],
        },
        {
            field: 'sourceGroupType_',
            title: '来源分组',
            minWidth: '140px',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'sourceCode_',
            title: '来源编号',
            minWidth: '140px',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'sourceName_',
            title: '来源名称',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'sourceVersion_',
            title: '来源版本号',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'sourceSuitableFund_',
            title: '来源适用产品',
            minWidth: '160px',
            sortable: true,
            filterType: 'funnel', // 下拉还是搜索
            filters: [],
        },
        {
            field: 'sourceStatus_',
            title: '来源状态',
            sortable: true,
            filterType: 'funnel',
            filters: DictionConstUtil.PojoToList3(this.Dict.sourceStatusPojo),
            render: value => this.Dict.sourceStatusPojo[value],
            style: value => {
                return {
                    color: {
                        '0': 'red',
                        '1': 'green',
                    }[value],
                };
            },
        },
        {
            field: 'termCreator_',
            title: '条款创建人',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'termCreatDate_',
            title: '条款创建时间',
            sortable: true,
        },
        {
            field: 'termModifier_',
            title: '条款更新人',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
        {
            field: 'termModuifyDate_',
            title: '条款更新时间',
            sortable: true,
        },
        {
            field: 'operation',
            title: '操作',
            fixed: 'right',
            width: 160,
            align: 'center',
            notShowTooltip: true,
        },
    ];
    fixedColumns: ColumnVO[] = [
        {
            field: 'termCode_',
            title: '条款编号',
            sortable: true,
            filterType: 'search',
            filters: [{ data: '' }],
        },
    ];
    tableKey: number = -1;
    showColumns: ColumnVO[] = [];
    searchParams: clauseManageReqVO = {
        keyword: '',
        termCode_: '',
        termId_: '',
        termName_: '',
        termRead_: '',
        suitableFund_: '',
        suitableExemptFund_: '',
        O32support_: '',
        Yhsupport_: '',
        sourceType_: '',
        sourceGroupType_: '',
        sourceCode_: '',
        sourceName_: '',
        sourceVisible_: '',
        sourceSuitableFund_: '',
        sourceStatus_: '',
        termCreator_: '',
        termCreatDate_: '',
        termModifier_: '',
        termModuifyDate_: '',
        showEffectSource: true,
    };
    // 重置请求参数模板(切换节点清除查询参数时用)
    clearParamsModel: clauseManageReqVO = {
        keyword: '',
        termCode_: '',
        termId_: '',
        termName_: '',
        termRead_: '',
        suitableFund_: '',
        suitableExemptFund_: '',
        O32support_: '',
        Yhsupport_: '',
        sourceType_: '',
        sourceGroupType_: '',
        sourceCode_: '',
        sourceName_: '',
        sourceVisible_: '',
        sourceSuitableFund_: '',
        sourceStatus_: '',
        termCreator_: '',
        termCreatDate_: '',
        termModifier_: '',
        termModuifyDate_: '',
        showEffectSource: true,
    };

    paging: PageVO = { currentPage: 1, pageSize: 25, total: 0 };

    tableLoading: boolean = false;
    btnType: string = '';
    currentRow: any = {};
    exportVisible: boolean = false;
    basicInfoVisible: boolean = false; // look|edit卡基本信息
    layoutDialog: boolean = false;
    deleteVisible: boolean = false;
    checkRowKeys: string[] = []; // 勾选keys
    exportName: string = ''; // 导出文件名

    @Prop() treeNodeData: any;
    /**
     * 左侧树节点的改变
     * 处理内容：查询条件重置（筛选条件）
     */
    @Watch('treeNodeData', { deep: true })
    changeNode() {
        // debugger;
        this.$nextTick(() => {
            const $Table = this.$refs['risk-table'] as any;
            const $xTable = $Table?.$refs['xTable'];
            ($xTable as any).clearFilter();
            this.searchParams = JSON.parse(JSON.stringify(this.clearParamsModel));
            // treeNodeData中的字段对应查询参数中的哪些 TODO
            this.getTableData();
        });
    }

    mounted() {
        // 监听布局设置
        this.$watch(
            () => {
                return (this.$refs['risk-table-layout'] as VueObject).showColumns;
            },
            val => {
                this.showColumns = val && val.length ? val : this.columns;
                this.tableKey++;
            }
        );
        this.getTableData();
    }
    /**
     * 获取表格列表
     */
    getTableData() {
        this.tableLoading = true;
        API.clauseManageList({ ...this.searchParams, paging: this.paging })
            .then((res: any) => {
                this.tableData = res.list;
                this.paging.total = res.total;
            })
            .finally(() => {
                this.tableLoading = false;
            });
    }
    /**
     * 分页、排序、筛选等
     */
    pageChange() {
        this.getTableData();
    }
    /**
     *
     * @operation 操作类型 search|add|delete|export|showEffectSource
     * @row 行数据
     */
    async handleBtn(operation: string): Promise<void> {
        console.log('预览查询|导入|导出|复选框改变:', operation);
        this.btnType = operation;

        if (operation == 'search') {
            this.paging.currentPage = 1;
            this.getTableData();
        } else if (operation === 'add') {
            this.basicInfoVisible = true;
            this.currentRow = {};
            this.currentRow.operationType = operation;
            this.currentRow.showDialogTitle = '新增条款';
        } else if (operation == 'delete') {
            this.checkRowKeys = (this.$refs['risk-table'] as any).checkRowKeys;
            if (this.checkRowKeys.length < 1) {
                this.yh_message_info('请先勾选需删除的条款!');
                return;
            }
            this.deleteVisible = true;
        } else if (operation === 'export') {
            // 导出时需要填写导出名称
            this.exportVisible = true;
        } else if (['showEffectSource'].includes(operation)) {
            this.paging.currentPage = 1;
            this.getTableData();
        }
    }

    /**
     * 操作行 type:look|edit|delete
     */
    handleRowData(type: string, row: any) {
        console.log('操作行:', type, row);
        this.currentRow = JSON.parse(JSON.stringify(row));
        this.currentRow.operationType = type;
        if (type == 'look') {
            this.currentRow.showDialogTitle = `查看条款(${this.currentRow.termCode_})`;
            this.basicInfoVisible = true;
        } else if (type == 'edit') {
            this.currentRow.showDialogTitle = `编辑条款(${this.currentRow.termCode_})`;
            this.basicInfoVisible = true;
        } else if (type == 'delete') {
            this.checkRowKeys = [row.termCode_];
            this.deleteVisible = true;
        }
    }

    /**
     * 查询弹框按钮处理
     */
    searchDialogBtn(type: string) {}

    /**
     * 查看、编辑
     */
    BasicDialogBtn(type: string) {
        if (type == 'cancel') {
            this.basicInfoVisible = false;
        } else if (type == 'confirm') {
            // 查看无需处理，编辑请求接口
            let info = (this.$refs['basic-info'] as any).basicForm;
            API.editClauseManage(info)
                .then((res: any) => {
                    this.yh_message_success('编辑成功!');
                })
                .catch(() => {})
                .finally(() => {
                    this.basicInfoVisible = false;
                });
        }
    }

    /**
     * 导出确认
     */
    async exportDialogBtn() {
        let checkRowKeys = (this.$refs['risk-table'] as any).checkRowKeys || [];
        await API.downLoadFileClauseManage({ ...this.searchParams, checkRowKeys, exportName: this.exportName });
        this.exportVisible = false;
    }

    /**
     * 删除弹框按钮处理 type:cancel|confirm
     */
    deleteDialogBtn(type: string) {
        if (type == 'cancel') {
            this.deleteVisible = false;
        } else if (type == 'confirm') {
            API.deleteClause({ termCode_: this.checkRowKeys })
                .then((res: any) => {
                    this.yh_message_success('删除成功！');
                    this.getTableData();
                })
                .finally(() => {
                    this.deleteVisible = false;
                });
        }
    }

    /**
     * 按钮权限设置
     */
    showAuthBtn(type: string) {
        let obj = {
            search: '',
            add: '',
            delete: '',
            import: '',
            export: '',
            layout: '',
            'row-look': '',
        };
        return 'B_0016';
        // return obj[type];
    }
}
</script>
<style lang="scss" scoped>
.main-content {
    height: 100%;
    .table-toolbar {
        padding: 12px;
        .item {
            margin-left: 10px;
        }
        .right-box {
            float: right;
        }
    }
    .table {
        height: calc(100% - 60px) !important;
    }
}

.vxe-input.size--mini {
    height: 26px;
    line-height: 36px;
}
/deep/ .el-textarea .el-textarea__inner {
    resize: none;
}

.basic-info-dialog {
    /deep/ .el-dialog .el-dialog__body {
        max-height: none;
        padding: 0 10px;
    }
}
</style>
